package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"sys-manager/sys-manager/cache"
	"sys-manager/sys-manager/modler"
	"time"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}

	var data = modler.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}

	err := modler.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	var article modler.Article
	redis_key := "article_error_" + strconv.Itoa(int(data.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		modler.DB.Create(&article)

		jsonData, _ := json.Marshal(article)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "ok",
		"data": article,
	})
	return

}

func List(c *gin.Context) {

	var article modler.Article
	modler.DB.Debug().Find(&article)
	redis_key := "list"
	cache.Rdb.Get(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "ok",
		"data": article,
	})
	return
}
